import network
import time
from machine import Pin
from oledprint import getI2Cstatue,threaded_print,OLEDPrinter
w=getI2Cstatue()
if w :
    oled_printer = OLEDPrinter(w)  
    global print  # 声明 print 为全局变量
    def print(*args, **kwargs):
        threaded_print(oled_printer,*args, **kwargs)
class NetworkManager:
    def __init__(self):
        self.led = Pin(2, Pin.OUT)
        self.led.value(0)

    def start_ap(self):
        ap = network.WLAN(network.AP_IF)
        ap.active(True)
        ap.config(essid='ESP32-Config', password="")  # 无密码的AP模式
        print("AP mode started. Connect to WiFi 'ESP32-Config' without password")
        print(ap.ifconfig())
        self.led.value(1)

    def connect_wifi(self, ssid, password):
        wlan = network.WLAN(network.STA_IF)
        wlan.active(True)
        if not wlan.isconnected():
            wlan.connect(ssid, password)
            for i in range(30):  # 尝试连接 30 次
                if wlan.isconnected():
                    print("WiFi connected!:", wlan.ifconfig())
                    self.led.value(0)
                    return True
                else:
                    self.led.value(1 if self.led.value() == 0 else 0)
                    time.sleep_ms(100)
                    print(f"retry connect WiFi{i + 1}...")
            raise Exception("WiFi connect false")
